#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cv2
import numpy as np
# import pytesseract
import sys
from matplotlib import pyplot as plt
import re
import os

import logging


def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    # handler = logging.FileHandler('log.txt', mode='w')
    # handler.setFormatter(formatter)
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    screen_handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    # logger.addHandler(handler)
    logger.addHandler(screen_handler)
    return logger


logger = setup_custom_logger('app')

# pytesseract.pytesseract.tesseract_cmd = "/usr/bin/tesseract"

images = {}


def pascalToCamel(x):
    s = re.sub('_([a-z])', lambda match: match.group(1).upper(), x)
    return s[:1].upper() + s[1:]


def camelToPascal(x):
    s = re.sub('([a-zA-Z])([A-Z])', lambda match: match.group(1).lower() + "_" + match.group(2).lower(), x)
    return s[:1].lower() + s[1:]


for (root, dirs, files) in os.walk('/home/liusen/IdeaWorkspace/wechat-jump/mijing3'):
    for item in files:
        filePath = os.path.join(root, item)
        s = os.path.splitext(item)[0]
        images[s] = cv2.cvtColor(cv2.imread(filePath), cv2.COLOR_BGR2GRAY)
        print('prepare image : ' + s)
        # os.rename(d, name)

location = {
    '01': [654, 678, 168, 186],
    '02': [654, 678, 168, 186],
    '03': [654, 678, 168, 186],
    '04': [654, 678, 168, 186],
    '05': [654, 678, 168, 186],
    '06': [654, 678, 168, 186],
    '07': [654, 678, 168, 186],
    '08': [654, 678, 168, 186],
    '09': [654, 678, 168, 186],
    'card_champion': [350, 386, 86, 156],
    'daily_task': [124, 156, 575, 705],
    'main_page': [382, 403, 417, 467],
    'match': [643, 670, 604, 674],
    'confirm': [616, 642, 598, 679],
    'end_round': [639, 698, 1188, 1239],
    'menu': [10, 70, 10, 70],
    'give_up': [276, 300, 609, 672],
    'click_to_continue': [666, 695, 587, 690],
    'participate_award': [88, 140, 545, 728],
    'log_back_in': [449, 481, 586, 692],
    'enter_game': [545, 578, 584, 693],
    'enter_round_2': [596, 614, 1196, 1231],
    'select_offensive_card': [35, 104, 551, 724],
    'select_defensive_card': [35, 104, 551, 724],
    'select_card': [115, 148, 514, 763],
    'level_1': [312, 387, 329, 408],
    'level_2': [312, 387, 329, 408],
    'level_3': [312, 387, 329, 408],
    'level_4': [312, 387, 329, 408],
    'level_5': [312, 387, 329, 408]
}


def detectImage(img, key, saveFlag=False, min=-1, max=-1):
    if key is None or key == '':
        plt.imshow(img), plt.show()
        return False

    # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    [a, b, c, d] = location[key]
    img = img[a:b, c:d]

    if min != -1 and max != -1:
        FILTER_MIN = np.array([min], np.uint8)
        FILTER_MAX = np.array([max], np.uint8)
        frame_threshed = cv2.inRange(img, FILTER_MIN, FILTER_MAX)
        img = cv2.bitwise_or(img, img, mask=frame_threshed)

    if saveFlag:
        cv2.imwrite('/home/liusen/IdeaWorkspace/wechat-jump/mijing3/{}.png'.format(key), img)
        return False

    template = images[key]

    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    logger.debug("{} match value : {}".format(key, res[0][0]))
    loc = np.where(res >= 0.93)

    # plt.subplot(221), plt.imshow(img)
    # plt.subplot(222), plt.imshow(template)
    # plt.show()

    if len(list(zip(*loc[::-1]))) == 1:
        return True
    else:
        return False


# for s in list(map(lambda x: '0' + str(x), range(1, 10))):
#     img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/{}.png'.format(s)),
#                        cv2.COLOR_BGR2GRAY)
#     detectImage(img, s, saveFlag=True)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/00019.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'card_champion', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/00027.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'daily_task', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/00026.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'main_page', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/00019.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'match', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/00001.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'confirm', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/end_round_2.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'end_round', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/end_round_2.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'menu', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/give_up.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'give_up', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/participate_award.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'participate_award', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/log_back_in.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'log_back_in', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/enter_game.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'enter_game', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/01.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'enter_round_2', saveFlag=False)

# img = cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/20180803.png')
# plt.imshow(img)
# # plt.subplot(132), plt.imshow(template)
# # plt.subplot(133), plt.imshow(diff)
# plt.show()


# detectImage(img, 'enter_round_2', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/20180804.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'select_offensive_card', saveFlag=False)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/20180804.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'select_card', saveFlag=False, min=250, max=255)

# img = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/201808-level-5.png'),
#                    cv2.COLOR_BGR2GRAY)
# detectImage(img, 'level_5', saveFlag=False, min=250, max=255)

def test6():
    # print(list(map(lambda x: '0' + str(x), range(1, 10))))
    for s in list(map(lambda x: '0' + str(x), range(1, 10))):
        srcPath = '/home/liusen/IdeaWorkspace/wechat-jump/mijing3/' + s + '.png'
        descPath = '/home/liusen/IdeaWorkspace/wechat-jump/mijing3/' + s + '_crop.png'
        img = cv2.imread(srcPath)
        img = img[654:678, 168:186]  # 回合数
        cv2.imwrite(descPath, img)


if __name__ == '__main__':
    # test6()
    sys.exit(0)
